import { login, logout, getInfo } from '@/api/services/login.service'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  luser: null,  // 登录用户信息
  lunitNum: '', // 登录用户所属车队编号
  uname: '',    // 登录用户名
  phone: '',    // 登录用户手机号
  name: ''      // 登录用户姓名
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_LUSER: (state, res) => {
    state.luser = res.data;
    state.lunitNum = res.lunitNum;
    state.uname = res.luser.uname;
    state.phone = res.luser.phone;
    state.name = res.luser.realName;
  }
}

const actions = {
  /**
   * 用户登录
   * @param {*} ps 用户登录参数
   */
  passLogin({ commit }, ps) {
    const { lphone, lpass } = ps;
    
    return new Promise((resolve, reject) => {
      
      login({ lphone: lphone, lpass: lpass }).then(data => {
        // 设置登录token至vue缓存
        commit('SET_TOKEN', data.uuid);
        
        // 设置登录token至本地缓存
        setToken(data.uuid);

        resolve(data);
      }).catch(error => {
        reject(error);
      });

    });
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        
        if (!response || response.code == 401) {
          reject('验证失败，请重新登录');
        }

        // commit('SET_LUSER', response);
        resolve(response);
      }).catch(error => {
        reject(error);
      });
    });
  },
  // 设置-用户信息至缓存
  setLInfo({ commit }, luser) {
    commit('SET_LUSER', luser);
  },

  // 用户登出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // 异步请求成功后再请求
      logout(state.token).then(() => {
        commit('SET_TOKEN', '');
        removeToken();

        // 重置访问的视图和缓存的视图
        dispatch('tagsView/delAllViews', null, { root: true }).then(() => {
          // 成功后才执行
          resolve();
        }).catch(error => {
          resolve(error);
        });
        
      }).catch(error => {
        reject(error);
      });

    });
  },

  // 删除登录token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
  
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
